{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "导入库：加载Scikit-learn、数据集及其他工具库。\n",
    "加载数据：导入或生成数据集，并进行必要的预处理。\n",
    "数据划分：将数据集划分为训练集和测试集。\n",
    "创建模型：使用RandomForestClassifier创建随机森林模型。\n",
    "训练模型：在训练集上训练随机森林模型。\n",
    "预测结果：在测试集上进行预测。\n",
    "评估性能：通过准确率等指标评估模型性能。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "只有一个数据集，进行数据的划分，训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import r2_score\n",
    " \n",
    "# 1. 加载训练集\n",
    "train = pd.read_csv('songs_train.csv')\n",
    "\n",
    "# 2. 分离特征和目标变量\n",
    "train_X = train.drop(['popularity'], axis=1)  # 特征\n",
    "train_y = train['popularity']                 # 目标变量\n",
    "\n",
    "# 3. 划分训练集和验证集\n",
    "X_train, X_val, y_train, y_val = train_test_split(train_X, train_y, test_size=0.2, random_state=42)\n",
    "\n",
    "# 4. 构建随机森林回归模型\n",
    "model = RandomForestRegressor(n_estimators=100, random_state=42)\n",
    "\n",
    "\n",
    "# 5. 训练模型\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "# 6. 在验证集上进行预测\n",
    "val_predictions = model.predict(X_val)\n",
    "\n",
    "# 7. 计算验证集上的 R² 得分\n",
    "r2 = r2_score(y_val, val_predictions)\n",
    "print(f\"验证集上的 R² 得分: {r2}\")\n",
    "\n",
    "# 8. 在整个训练集上进行预测（模拟对测试集的预测）\n",
    "train_predictions = model.predict(train_X)\n",
    "\n",
    "# 9. 将预测结果保存到训练集的 'popularity' 列\n",
    "train['predicted_popularity'] = train_predictions\n",
    "\n",
    "# 10. 保存预测结果为 'songs_train_predictions.csv'，仅用于展示模型在训练集上的表现\n",
    "train.to_csv('songs_train_predictions.csv', index=False)\n",
    "print(\"预测结果已保存至 songs_train_predictions.csv\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "已经划分训练集和测试集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.metrics import r2_score\n",
    "\n",
    "# 1. 加载训练集和测试集\n",
    "train = pd.read_csv('songs_train.csv')\n",
    "test = pd.read_csv('songs_test.csv')\n",
    "\n",
    "# 2. 分离特征和目标变量\n",
    "train_X = train.drop(['popularity'], axis=1)  # 特征\n",
    "train_y = train['popularity']                 # 目标变量\n",
    "test_X = test.drop(['popularity'], axis=1)    # 测试集的特征\n",
    "\n",
    "# 3. 构建随机森林回归模型\n",
    "model = RandomForestRegressor(n_estimators=100, random_state=42)\n",
    "\n",
    "\n",
    "# 4. 训练模型\n",
    "model.fit(train_X, train_y)\n",
    "\n",
    "# 5. 在训练集上进行预测并计算训练集的 R² 得分\n",
    "train_predictions = model.predict(train_X)\n",
    "r2 = r2_score(train_y, train_predictions)\n",
    "print(f\"训练集上的 R² 得分: {r2}\")\n",
    "\n",
    "# 6. 使用训练好的模型对测试集进行预测\n",
    "test_predictions = model.predict(test_X)\n",
    "\n",
    "# 7. 将预测结果填充到测试集的 'popularity' 列\n",
    "test['popularity'] = test_predictions\n",
    "\n",
    "# 8. 保存预测结果到 'songs_testout.csv'，保留测试集的原始数据并填充 'popularity' 列\n",
    "test.to_csv('songs_testout.csv', index=False)\n",
    "print(\"预测结果已保存至 songs_testout.csv\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "带有超参数的设置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最佳超参数组合： {'criterion': 'gini', 'max_depth': 4, 'min_samples_leaf': 3, 'min_samples_split': 2}\n",
      "最佳模型的测试集准确率: 1.00\n",
      "测试集预测结果: [1 0 2 1 1 0 1 2 1 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0 0 0 1 0 0 2 1\n",
      " 0 0 0 2 1 1 0 0]\n"
     ]
    }
   ],
   "source": [
    "# 导入必要的库\n",
    "import numpy as np\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split, GridSearchCV\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.metrics import accuracy_score\n",
    "\n",
    "# 加载鸢尾花数据集\n",
    "data = load_iris()\n",
    "X = data.data\n",
    "y = data.target\n",
    "\n",
    "# 将数据分为训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
    "\n",
    "# 定义超参数的搜索范围\n",
    "param_grid = {\n",
    "    'max_depth': [3, 4, 5, 6],          # 树的最大深度\n",
    "    'min_samples_split': [2, 3, 4, 5],  # 分裂一个节点所需的最小样本数\n",
    "    'min_samples_leaf': [1, 2, 3],      # 叶子节点上的最小样本数\n",
    "    'criterion': ['gini', 'entropy']    # 划分标准\n",
    "}\n",
    "\n",
    "# 创建决策树分类器\n",
    "clf = DecisionTreeClassifier()\n",
    "\n",
    "# 使用网格搜索来寻找最佳的超参数组合\n",
    "grid_search = GridSearchCV(clf, param_grid, cv=5, scoring='accuracy')\n",
    "\n",
    "# 在训练集上训练模型\n",
    "grid_search.fit(X_train, y_train)\n",
    "\n",
    "# 输出最佳的超参数组合\n",
    "print(\"最佳超参数组合：\", grid_search.best_params_)\n",
    "\n",
    "# 使用最佳模型在测试集上进行预测\n",
    "best_model = grid_search.best_estimator_\n",
    "y_pred = best_model.predict(X_test)\n",
    "\n",
    "# 计算并输出测试集上的准确率\n",
    "accuracy = accuracy_score(y_test, y_pred)\n",
    "print(f\"最佳模型的测试集准确率: {accuracy:.2f}\")\n",
    "\n",
    "# 输出测试集上的预测结果\n",
    "print(\"测试集预测结果:\", y_pred)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最佳超参数组合： {'bootstrap': True, 'max_depth': 4, 'min_samples_leaf': 1, 'min_samples_split': 2, 'n_estimators': 100}\n",
      "最佳模型的测试集准确率: 1.00\n",
      "测试集预测结果: [1 0 2 1 1 0 1 2 1 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0 0 0 1 0 0 2 1\n",
      " 0 0 0 2 1 1 0 0]\n"
     ]
    }
   ],
   "source": [
    "# 导入必要的库\n",
    "import numpy as np\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split, GridSearchCV\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.metrics import accuracy_score\n",
    "\n",
    "# 加载鸢尾花数据集\n",
    "data = load_iris()\n",
    "X = data.data\n",
    "y = data.target\n",
    "\n",
    "# 将数据分为训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
    "\n",
    "# 定义随机森林的超参数网格\n",
    "param_grid = {\n",
    "    'n_estimators': [50, 100, 200],             # 决策树的数量\n",
    "    'max_depth': [4, 6, 8, 10],                 # 树的最大深度\n",
    "    'min_samples_split': [2, 5, 10],            # 分裂节点的最小样本数\n",
    "    'min_samples_leaf': [1, 2, 4],              # 叶子节点的最小样本数\n",
    "    'bootstrap': [True, False]                  # 是否使用有放回的采样\n",
    "}\n",
    "\n",
    "# 创建随机森林分类器\n",
    "rf = RandomForestClassifier(random_state=42)\n",
    "\n",
    "# 使用网格搜索进行超参数调优\n",
    "grid_search = GridSearchCV(estimator=rf, param_grid=param_grid, cv=5, scoring='accuracy', n_jobs=-1)\n",
    "\n",
    "# 在训练集上训练模型\n",
    "grid_search.fit(X_train, y_train)\n",
    "\n",
    "# 输出最佳的超参数组合\n",
    "print(\"最佳超参数组合：\", grid_search.best_params_)\n",
    "\n",
    "# 使用最佳模型在测试集上进行预测\n",
    "best_model = grid_search.best_estimator_\n",
    "y_pred = best_model.predict(X_test)\n",
    "\n",
    "# 计算并输出测试集上的准确率\n",
    "accuracy = accuracy_score(y_test, y_pred)\n",
    "print(f\"最佳模型的测试集准确率: {accuracy:.2f}\")\n",
    "\n",
    "# 输出测试集上的预测结果\n",
    "print(\"测试集预测结果:\", y_pred)\n",
    "                                                               "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| **场景**                     | **描述**                                                                 | **代码示例**                                                                                   |\n",
    "|------------------------------|--------------------------------------------------------------------------|------------------------------------------------------------------------------------------------|\n",
    "| **单行字符串**               | 使用单引号或双引号包裹单行文本。                                          | ```python<br>text1 = '这是一个单行字符串。'<br>text2 = \"这也是一个单行字符串。\"```             |\n",
    "| **多行字符串**               | 使用三引号包裹多行文本。                                                  | ```python<br>text = \\\"\\\"\\\"这是第一行<br>这是第二行<br>这是第三行\\\"\\\"\\\"```                     |\n",
    "| **字符串拼接**               | 使用 `+` 拼接多个字符串。                                                 | ```python<br>str1 = 'Hello'<br>str2 = 'World'<br>result = str1 + ', ' + str2 + '!'```          |\n",
    "| **字符串格式化**             | 使用 `f-string` 格式化字符串。                                            | ```python<br>name = 'Alice'<br>age = 25<br>text = f'我的名字是 {name}，我 {age} 岁了。'```     |\n",
    "| **字符串转义**               | 使用反斜杠 `\\` 转义特殊字符。                                             | ```python<br>text = '这是一个带引号的字符串：\\\\'Hello\\\\''```                                   |\n",
    "| **字符串切片**               | 使用切片操作获取子字符串。                                                | ```python<br>text = 'Hello, World!'<br>substring = text[0:5]  # 输出: 'Hello'```               |\n",
    "| **字符串替换**               | 使用 `replace()` 方法替换字符串中的部分内容。                             | ```python<br>text = 'Hello, World!'<br>new_text = text.replace('World', 'Python')```           |\n",
    "| **字符串分割**               | 使用 `split()` 方法将字符串拆分为列表。                                   | ```python<br>text = 'apple,banana,cherry'<br>fruits = text.split(',')  # 输出: ['apple', 'banana', 'cherry']``` |\n",
    "| **字符串连接**               | 使用 `join()` 方法将列表中的字符串连接为一个字符串。                      | ```python<br>fruits = ['apple', 'banana', 'cherry']<br>text = ', '.join(fruits)  # 输出: 'apple, banana, cherry'``` |\n",
    "| **字符串大小写转换**         | 使用 `upper()` 和 `lower()` 方法转换字符串大小写。                        | ```python<br>text = 'Hello, World!'<br>upper_text = text.upper()  # 输出: 'HELLO, WORLD!'<br>lower_text = text.lower()  # 输出: 'hello, world!'``` |\n",
    "| **字符串去除空白**           | 使用 `strip()` 方法去除字符串两端的空白字符。                             | ```python<br>text = '  Hello, World!  '<br>stripped_text = text.strip()  # 输出: 'Hello, World!'``` |\n",
    "| **字符串查找**               | 使用 `find()` 方法查找子字符串的位置。                                    | ```python<br>text = 'Hello, World!'<br>position = text.find('World')  # 输出: 7```             |\n",
    "| **字符串检查**               | 使用 `startswith()` 和 `endswith()` 方法检查字符串的开头或结尾。          | ```python<br>text = 'Hello, World!'<br>starts_with_hello = text.startswith('Hello')  # 输出: True<br>ends_with_world = text.endswith('World!')  # 输出: True``` |\n",
    "| **字符串长度**               | 使用 `len()` 函数获取字符串的长度。                                       | ```python<br>text = 'Hello, World!'<br>length = len(text)  # 输出: 13```                       |\n",
    "| **字符串反转**               | 使用切片操作反转字符串。                                                  | ```python<br>text = 'Hello, World!'<br>reversed_text = text[::-1]  # 输出: '!dlroW ,olleH'```  |"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
